<template>
    <!-- 编辑   -->
    <public-dialog
            :title="'编辑'"
            :width="'50%'"
            v-model:visible="visible"
            :confirm-button-title="'提交'"
            @on-confirm="onConfirm"
    >
        <template #default>
            <div class="page">
                <el-form
                        ref="formRef"
                        label-width="100"
                        :model="form"
                        :rules="rules"
                        class="d-flex"
                >
                    <div class="left-wrap">
                        <div class="d-flex a-center">
                            <el-form-item label-width="80px" label="投资方案" prop="urlKey">
                                <el-upload
                                        ref="uploadRef"
                                        action="#"
                                        :limit="1"
                                        :http-request="uploadFile"
                                        :on-remove="onRemove"
                                >
                                    <el-button  style="border-color: #FC7018;background-color:#fff8f6;color: #FC7018;">
                                        <svg-icon icon-class="project-detail-icon-l-shangchuan" class="upload-icon m-r5"></svg-icon>
                                        点击上传
                                    </el-button>
                                </el-upload>
                            </el-form-item>
                        </div>
                        <div class="box m-t20">
                            <label>方案预览:</label>
                            <div ref="contractContentRef" class="contract-content m-t10" id="demoDocContainer">

                            </div>
                        </div>
                    </div>
                    <div class="line"></div>
                    <div class="right-wrap">
                        <div style="opacity: 0">
                            <label style="color: #1A1A1A;"></label>
                            <el-button class="m-l10" style="border-color: #FC7018;background-color:#fff8f6;color: #FC7018;">
                            </el-button>
                        </div>
                        <div class="box m-t20">
                            <label>关键信息编制：</label>
                            <div class="form-content m-t30">

                                <el-form-item label="方案名称" prop="planName">
                                    <el-input v-model="form.planName" placeholder="请输入方案名称"></el-input>
                                </el-form-item>
                                <el-form-item label="方案描述" prop="planSummary">
                                    <el-input v-model="form.planSummary" placeholder="请输入方案描述"></el-input>
                                </el-form-item>
                                <el-form-item label="预算金额" prop="planAmount">
                                    <el-input
                                            v-model="form.planAmount"
                                            placeholder="请输入预算金额"
                                            @input="form.planAmount = limitInputNum(form.planAmount,8,2,true)"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="注册资本" prop="registerCapital">
                                    <el-input
                                            v-model="form.registerCapital"
                                            placeholder="请输入注册资本"
                                            @input="form.registerCapital = limitInputNum(form.registerCapital,8,2,true)"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="投资比例" prop="investmentRatio">
                                    <el-input
                                            v-model="form.investmentRatio"
                                            placeholder="请输入投资比例"
                                            @input="form.investmentRatio = limitInputNum(form.investmentRatio,3,0,false)"
                                    ></el-input>
                                </el-form-item>
                                <el-form-item label="合作方" prop="partnerId">
                                    <el-select v-model="form.partnerId" class="input-width" clearable>
                                        <el-option v-for="(item,index) in state.partnerList" :key="index" :label="item.partnerName" :value="item.partnerId"></el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                        </div>
                    </div>
                </el-form>
            </div>
        </template>
    </public-dialog>
</template>

<script setup>
import PublicDialog from "@/components/PublicDialog.vue";
import {nextTick, onMounted, reactive, ref} from "vue";
import {ElForm, ElFormItem, ElUpload, ElSelect, ElOption, ElMessage, ElLoading} from "element-plus";
import {programmeManagementApi, reserveInvestmentProjectLibraryApi} from "@/api/investment";
import {renderAsync} from "docx-preview";
import {limitInputNum} from "@/common/utils/GlobalUtils";

const visible = ref(false);
const state = reactive({
    status:0,
    programme:{},
    partnerList:[]
});

const docxOptions =  {
    className: "kaimo-docx-666", // string：默认和文档样式类的类名/前缀
    inWrapper:  true, // boolean：启用围绕文档内容的包装器渲染
    ignoreWidth: false, // boolean：禁用页面的渲染宽度
    ignoreHeight: false, // boolean：禁止渲染页面高度
    ignoreFonts: false, // boolean：禁用字体渲染
    breakPages: true, // boolean：在分页符上启用分页
    ignoreLastRenderedPageBreak: true, // boolean：在 lastRenderedPageBreak 元素上禁用分页
    experimental: false, // boolean：启用实验功能（制表符停止计算）
    trimXmlDeclaration: true,  // boolean：如果为true，解析前会从 xml 文档中移除 xml 声明
    useBase64URL: false, // boolean：如果为true，图片、字体等会转为base 64 URL，否则使用URL.createObjectURL
    useMathMLPolyfill: false, // boolean：包括用于 chrome、edge 等的 MathML polyfill。
    showChanges: false, // boolean：启用文档更改的实验性渲染（插入/删除）
    debug: false, // boolean：启用额外的日志记录
}

const form = reactive({
    operation:1, // 1-方案管理编辑 2-立项变更编辑
    planName:'',
    planSummary:'',
    planAmount:'',
    registerCapital:'',
    investmentRatio:'',
    partnerId:'',
    projectId:'',
    planId:'',
    urlKey:'',
    currentFile:null
});

const rules = reactive({
    planName: [
        { required: true, message: '方案名称不能为空!', trigger: 'blur' },
    ],
    planSummary: [
        { required: true, message: '方案描述不能为空!', trigger: 'blur' },
    ],
    planAmount: [
        { required: true, message: '计划金额不能为空!', trigger: 'blur' },
    ],
    registerCapital: [
        { required: true, message: '注册资本不能为空!', trigger: 'blur' },
    ],
    investmentRatio: [
        { required: true, message: '投资比例不能为空!', trigger: 'blur' },
    ],
    partnerId: [
        { required: true, message: '合作方不能为空!', trigger: 'change' },
    ],
    investmentScale: [
        { required: true, message: '投资规模不能为空!', trigger: 'blur' },
    ],
    urlKey: [
        { required: true, message: '投资方案不能为空!', trigger: 'change' },
    ],
});

/**
 * 根据项目名称获取渲染后的word
 * @param templateUrlKey
 */
const contractContentRef = ref(null);
const getPlanWord = (templateUrlKey) => {
    reserveInvestmentProjectLibraryApi.getPlanWord({templateUrlKey:templateUrlKey}).then(res=>{
        if(res){
            let blob = new Blob([res],{
                type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
            });

            nextTick(()=>{
                renderAsync(blob, contractContentRef.value,null,docxOptions);
            });
        }
    });
}

/**
 * 查询方案信息详情
 * @param planId
 */
const getProgramme = (planId) => {
    programmeManagementApi.getProgramme({planId:planId}).then(res=>{
        const {code,data } = res;
        if(code == 200){
            if(data.fileUrlKey!==''){
                form.urlKey = data.fileUrlKey;
                getPlanWord(data.fileUrlKey);
            }
            for (let k1 in data){
                for (let k2 in form){
                    if(k1 === k2){
                       form[k2] = data[k1];
                    }
                }
            }
        }
    });
}

/**
 * 合作方
 */
const getAllPartner = () => {
    reserveInvestmentProjectLibraryApi.getAllPartner().then(res=>{
        const {code,data} = res;
        if(code == 200){
            state.partnerList = data;
        }
    });
}


const docxRender = (buffer) => {
    let bodyContainer = document.getElementById("demoDocContainer");
    renderAsync(
        buffer, // Blob | ArrayBuffer | Uint8Array, 可以是 JSZip.loadAsync 支持的任何类型
        bodyContainer, // HTMLElement 渲染文档内容的元素,
        null, // HTMLElement, 用于呈现文档样式、数字、字体的元素。如果为 null，则将使用 bodyContainer。
        docxOptions // 配置
    ).then(res => {
        console.log("res---->", res)
    });
}

/**
 * el-upload 选择文件后的事件
 * @param file
 */
const formRef = ref(null);
const uploadFile = (file) => {
    form.currentFile = file.file;
    formRef.value.clearValidate('currentFile');
    const downUrl = URL.createObjectURL(file.file)
    const a = document.createElement('a');
    a.innerHTML = file.file.name;
    a.href = downUrl
    a.download = file.file.name;
    a.target = '_blank';
    const addTypeArray = file.file.name.split(".");
    const addType = addTypeArray[addTypeArray.length - 1]

    if(addType === "doc" || addType === "docx" || addType === "word"){
        // 将file转为buffer
        let fr = new FileReader();
        fr.readAsArrayBuffer(file.file);
        fr.addEventListener("loadend",(e) => {
            let buffer = e.target.result;
            docxRender(buffer);
        },false);

    }else{
        ElMessage.error('请上传正确格式的文档!');
    }
}

/**
 * 文件移除
 */
const onRemove = () => {
    form.urlKey = '';
    form.currentFile = null;
    formRef.value.validateField('urlKey');
}

/**
 * 编辑确认
 */
const emits = defineEmits(['onSuccess']);
const onConfirm = () => {
    formRef.value.validate(async (valid, fields) => {
        if (valid) {
            let  loading = null;
            try {
                loading = ElLoading.service({
                    lock: true,
                    text: '提交表单中...',
                    background: 'rgba(0, 0, 0, 0.7)',
                })
                if(form.urlKey==='' && form.currentFile !==null){
                    let uploadFile = new FormData();
                    uploadFile.append("file",form.currentFile);
                    const res = await reserveInvestmentProjectLibraryApi.upload(uploadFile);
                    form.urlKey = res.data;
                }
                const res2 = await programmeManagementApi.editForApproval(form)
                if(res2.code == 200){
                    loading.close();
                    visible.value = false;
                    ElMessage.success('提交成功!');
                    emits('onSuccess');
                }
            }catch (e) {
                loading.close();
                ElMessage.error('提交表单异常!');
            }
        } else {
            console.log('error submit!', fields)
        }
    });
}

/**
 * 打开
 */
const open = (row) => {
    state.status = row.status;
    getProgramme(row.planId);
    visible.value = true;
}

/**
 * 关闭
 */
const close = () => {
    visible.value = false;
}

onMounted(()=>{
    getAllPartner();
});

defineExpose({
    open,
    close,
});
</script>

<style>
.contract-content .kaimo-docx-666-wrapper{
    background: none;
}
</style>

<style lang="scss" scoped>
.upload-icon{
  width: 18px;
  height: 18px;
}
.page{
  position: relative;
  .left-wrap{
    flex: 1;
    .box{
      width: 100%;
      height: 627px;
      .contract-content{
        width: 500px;
        height: 600px;
        background-color: #d8d8d8;
        border: 1px solid #979797;
        border-radius: 5px;
        overflow: auto;
      }
    }
  }
  .line{
    width: 1px;
    height: 70vh;
    background-color: #E3E7F1;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(- 50%,- 50%) scaleX(.5);
  }
  .right-wrap{
    flex: 1;
    margin-left: 100px;
    margin-top: 18px;
  }
}

.head-warp{
  .file-icon{
    width: 16px;
    height: 16px;
  }
  .download{
    font-size: 14px;
    font-family: SourceHanSansCN-Medium, SourceHanSansCN;
    font-weight: 500;
    color: #FC7018;
    border-bottom: 1px solid #FC7018;
    cursor: pointer;
  }
  .time-icon{
    width: 22px;
    height: 22px;
  }
  .status{
    font-size: 14px;
    font-family: SourceHanSansCN-Normal, SourceHanSansCN;
    font-weight: 400;
    color: #D15609;
  }
}
.content-wrap{
  .left-wrap{
    .word-content{
      width: 347px;
      height: 500px;
      background: #D8D8D8;
      border: 1px solid #979797;
      overflow: auto;
    }
  }
  .line{
    width: 1px;
    height: 500px;
    background: #E3E7F1;
  }
  .right-wrap{

  }
}
.footer-wrap{
  width: 100%;
  border-top: 1px solid #E3E7F1;
}
</style>